//app.js
import {
  envid,
  apiBaseUrl,
} from '../config.js';

console.log(envid)

import {
  storagerWxopenidAndUserInfo
} from './storagerWxopenidAndUserInfo'

//云开发的初始化
wx.cloud.init({
  env: envid,
  traceUser: true,
})

var app = getApp();

class WxUserManager {
  constructor() {

  }

  checkWxopenidInStorageAtMypage() { //当前项目的Mypage 是 /page/*/five 模块, 该函数在该模块执行
    if (wxopenid) {
      this.fethUserInfoFromBackendFlow(wxopenid);
    } else {
      // this.startAuthFlow();
      wx.navigateTo({
        url: '/page/index/index', //这是授权登录页面
      })
    }
  }

  // 获取用户openid
  startAuthFlowAtLoginpage() { //当前项目login页是 /page/index/index 模块, 该函数在该模块执行
    var that = this;
    var wxopenidCached = wx.getStorageSync('openid');
    if (openidCached) {
      console.log('本地获取openid:' + wxopenidCached);
      app.globalData.openid = wxopenidCached;
      app.fetchUserInfoFromBackendFlow();
    } else {
      //获取openid不需要授权
      wx.cloud.callFunction({
        name: "getOpenid",
        success(res) {
          var wxopenid = res.result.openid;
          app.globalData.openid = wxopenid;
          console.log('请求获取openid:', wxopenid);
          wx.setStorageSync('openid', wxopenid)
          // app._getUserInfo();
          app.fetchUserInfoFromBackendFlow(wxopenid);
        },
        fail(res) {
          wx.navigateBack({
            delta: 1,
          });
          // app._getUserInfo();
          // app.fetchUserInfoFromBackendFlow(wxopenid);
        }
      })
    }
    app.globalData.isAdmin = app.globalData.openid === adminWxOpenid; // 判断当前用户是否admin管理员存到app.globalData保存
  }
  
}

export const wxUserManager = new WxUserManager();